package leetCode.solution;

import java.util.Iterator;
import java.util.stream.Stream;

/**
 * 给定一个包含非负整数的 m x n 网格 grid ，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 * 
 * @author jerry
 * @ClassName: Solution64
 * @Description:TODO(描述这个类的作用)
 * @date 2022年11月23日 下午2:05:50
 */
public class Solution64 {
	
	public static void main(String[] args) {
		new Solution64().test();
	}
	
	private void test() {
		int mMax = 5;
		int nMax = 5;
		int valueMax = 10;
		Stream.iterate(0, i->i+1).limit(500000).forEach(i->{
			int m = (int)(Math.random()*mMax);
			int n = (int)(Math.random()*nMax);
			int [][]arr = new int[m][n];
			Stream.iterate(0, mm->mm+1).limit(m).forEach(mm->{
				Stream.iterate(0, nn->nn+1).limit(n).forEach(nn->{
					arr[mm][nn]=(int)(Math.random()*valueMax);
				});
			});
			if(minPathSum(arr)!=minPathSum1(arr)) {
				System.out.println("Oops!");
			}
		});
	}

	
	public int minPathSum(int[][] grid) {
		if(grid==null || grid.length<1|| grid[0].length<1) return 0;
		return walk(grid, 0, 0, 0);
	}
	
	public int walk(int[][] grid, int i, int j, int sum) {
		if(i==grid.length-1 && j==grid[0].length-1) {
			return sum+grid[i][j];
		}
		if(i==grid.length-1) {
			return walk(grid, i, j+1, sum+grid[i][j]);
		}
		if(j==grid[0].length-1) {
			return walk(grid, i+1, j, sum+grid[i][j]);
		}
		
		int jwalk = walk(grid, i, j+1, sum+grid[i][j]);
		
		int iwalk = walk(grid, i+1, j, sum+grid[i][j]);
		
		return Math.min(jwalk, iwalk);
	}
	
	public int minPathSum1(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int rows = grid.length, columns = grid[0].length;
        int[][] dp = new int[rows][columns];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < rows; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int j = 1; j < columns; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < columns; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[rows - 1][columns - 1];
    }
	
}
